傳統If應用如下:
var max: Int
if (a > b) {
max = a
} else {
max = b
}
可用單行表達式
val max = if (a > b) a else b
Kotlin中採用when關鍵字取代switch
使用方式如下
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
如果when多個條件皆處理相同的事物
則可以合併在一起
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
when的條件除了用常數之外也可用函數表示
when (x) {
parseInt(s) -> print("s encodes x")
esle -> print("s does not encode x")
}
也可用in跟in!關鍵字判斷是否在某個range內
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
用is跟is!檢查參數是否為某種類型(type)
fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix") //x 被自動轉型為string
else -> false
}
取代if-else判斷式
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}
For迴圈語法語C#相似
for (item in collection) print(item)
withIndex 可同時獲得key跟value值
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
沒甚麼大變化
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null)